//
//  DetailViewModel.swift
//  shop
//
//  Created by chen on 2025/5/14.
//

import SwiftUI

@MainActor
class DetailViewModel: ObservableObject {
    
    static let shared: DetailViewModel = DetailViewModel()
    
    public init() {}
    
    @Published var itemDetail: ItemDetail = ItemDetail()
    
    @Published var bannerList: [String] = []
    
    @Published var goodsDetail: GoodsDetail = GoodsDetail()
    
    @Published var likeGoodsList: [GoodsItem] = []
    
    public func getItemDetail(itemid: String) {
        Task{
            let queryParam: [String:Any] = [
                "apiKey": ApiKey.haodanku.rawValue,
                "itemid": itemid
            ]
            
            await NetManager.shared.httpGet(.itemDetail, queryParam: queryParam) { (data: ItemDetail) in
                self.itemDetail = data
                
                if !data.taobao_image.isEmpty {
                    self.bannerList = data.taobao_image.components(separatedBy: ",")
                }
            }
        }
    }
    
    public func getGoodsDetail(id: Int64) {
        Task{
            let queryParam: [String:Any] = [
                "version": "v1.2.3",
                "id": id
            ]
            
            await NetManager.shared.httpGet(.getGoodsDetails, queryParam: queryParam) { (data: GoodsDetail) in
                self.goodsDetail = data
                
                if !data.imgs.isEmpty {
                    self.bannerList = data.imgs.components(separatedBy: ",")
                }
                
                self.getLikeGoodsList()
            }
        }
    }
    
    private func getLikeGoodsList() {
        Task{
            if goodsDetail.itemLink.isEmpty {
                return
            }
            
            await NetManager.shared.processURL(goodsDetail.itemLink) { (param:[String:String]?) in
                let id = param?["id"] ?? ""
                if id.isEmpty {
                    return
                }
                
                let queryParam:[String:Any] = [
                    "version": "v1.2.2",
                    "id": id,
                    "size": 10
                ]
                
                await NetManager.shared.httpGet(.similerList, queryParam: queryParam) { (data: [GoodsItem]) in
                    self.likeGoodsList = data
                }
            }
        }
    }
}
